package com.csun.cmny.provider.controller.admin;

import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.device.phone.entity.PhoneConstant;
import com.csun.cmny.provider.model.domain.*;
import com.csun.cmny.provider.model.dto.mohe.*;
import com.csun.cmny.provider.model.enums.device.DeviceStatusEnum;
import com.csun.cmny.provider.model.enums.device.DmcDeviceTypeEnum;
import com.csun.cmny.provider.model.vo.OldmanBedRoomBuildingVo;
import com.csun.cmny.provider.model.vo.RoomBuildingVo;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.util.RedisKeyUtil;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaoleilu.hutool.util.BeanUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping(value = "/mohe", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class DmcMoheController extends BaseController {

    @Resource
    private DmcMoheService dmcMoheService;

    @Resource
    private DmcMoheDeviceInfoService moheDeviceInfoService;

    @Resource
    private DmcDeviceService dmcDeviceService;

    @Resource
    private CmnyMessageSource cmnyMessageSource;

    @Resource
    private DmcMoheDeviceRelationService moheDeviceRelationService;

    @Resource
    private DmcCsunMoheLocationService moheLocationService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private DmcDeviceAlertService dmcDeviceAlertService;


    @RequestMapping(value = "/getCallToken", method = RequestMethod.POST)
    public Wrapper getCallToken(@RequestParam Map<String, Object> params){
        log.info("/mohe/getCallToken: getMapData");
        for (String mp : params.keySet()) {
            log.info("key = " + mp + ", value = " + params.get(mp));
        }
        String sn = (String) params.get("device_serial_num");
        //根据编号查询设备
        Example example = new Example(DmcDevice.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deviceNo", sn);
        List<DmcDevice> dmcDevices = dmcDeviceService.selectByExample(example);
        if (CollectionUtil.isEmpty(dmcDevices)) {
            log.info("当前设备未注册");
            return WrapMapper.wrap(Wrapper.ERROR_CODE, "当前设备未注册");
        }
        DmcDevice moheDeviceInfo = dmcDevices.get(0);
        if (moheDeviceInfo != null) {
            String groupToken = moheDeviceInfo.getGroupId()+"-234567890f0f0f0f887766557733aabb";
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "获取成功", groupToken);
        }else{
            log.info("当前设备未注册");
            return WrapMapper.wrap(Wrapper.ERROR_CODE, "当前设备未注册");
        }
    }

    /**
     * 用户登录数据推送
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Wrapper login(@RequestParam Map<String, Object> params) {
        //@RequestParam Map<String, Object> params
        log.info("/mohe/login,loginDto: getMapData");
        for (String mp : params.keySet()) {
            log.info("key = " + mp + ", value = " + params.get(mp));
        }
        String sn = (String) params.get("device_serial_num");
        String topicTome = (String) params.get("topic_tome");
        String userName = (String) params.get("user_name");
        log.info("/mohe/login,loginDto: sn : "+sn);
        log.info("/mohe/login,loginDto: token : "+topicTome);
        Example example = new Example(DmcDevice.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deviceNo", sn);
        List<DmcDevice> dmcDevices = dmcDeviceService.selectByExample(example);
        if (CollectionUtil.isEmpty(dmcDevices)) {
            log.info("当前设备未注册");
        }
        Long id = dmcDevices.get(0).getId();
        DmcMoheDeviceInfo dmcMoheDeviceInfo = moheDeviceInfoService.selectByKey(id);
        DmcMoheDeviceInfo moheDeviceInfo = new DmcMoheDeviceInfo();
        log.info("dmcDevicesId "+ id);

        // 保存魔盒token
        if (dmcMoheDeviceInfo == null) {
            moheDeviceInfo.setDeviceId(id);
            moheDeviceInfo.setToken(topicTome);
            moheDeviceInfo.setUserId(userName);
            moheDeviceInfoService.save(moheDeviceInfo);
            redisTemplate.opsForValue().set(moheDeviceInfo.getUserId(), moheDeviceInfo);

        } else {
            moheDeviceInfo.setDeviceId(id);
            moheDeviceInfo.setToken(topicTome);
            moheDeviceInfo.setUserId(userName);
            moheDeviceInfoService.update(moheDeviceInfo);
            redisTemplate.opsForValue().set(moheDeviceInfo.getUserId(), moheDeviceInfo);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE);
    }

    /**
     * 设备报警数据推送
     */
    @RequestMapping(value = "/alarmReceive", method = RequestMethod.POST)
    public Wrapper alarmReceive(@RequestBody AlarmReceiveDto alarmReceiveDto) {
        log.info("/mohe/alarmReceive,alarmReceiveDto:" + alarmReceiveDto.toString());
        String recordList = alarmReceiveDto.getRecordList();
        String sn = alarmReceiveDto.getDeviceSerialNum();

        Example example = new Example(DmcDevice.class);
        example.createCriteria().andEqualTo("deviceNo", sn);
        List<DmcDevice> dmcDevices = dmcDeviceService.selectByExample(example);
        if (CollectionUtil.isEmpty(dmcDevices)) {
            log.info("根据sn:{}，未找到设备", sn);
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE);
        }
        DmcDevice dmcDevice = dmcDevices.get(0);

        JSONArray jsonArray = JSONArray.fromObject(recordList);
        List<MoheRecord> list = JSONArray.toList(jsonArray, MoheRecord.class);
        if (CollectionUtil.isEmpty(list)) {
            log.info("当前报警数据为空");
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE);
        }

        DmcCsunMoheLocation moheLocation = moheLocationService.selectByKey(dmcDevice.getId());

        for (MoheRecord moheRecord : list) {
            DmcDeviceAlert deviceAlert = new DmcDeviceAlert();
            if (moheLocation != null) {
                if (moheLocation.getBindType() == 0) {
                    deviceAlert.setLocation(moheLocation.getLocation());
                } else if (moheLocation.getBindType() == 1) {
                    deviceAlert.setLocation(moheLocation.getOldmanName());
                    deviceAlert.setOldmanId(moheLocation.getOldmanId());
                    deviceAlert.setOldmanName(moheLocation.getOldmanName());
                } else if (moheLocation.getBindType() == 2) {
                    deviceAlert.setLocation(moheLocation.getBedId() + "");
                } else if (moheLocation.getBindType() == 3) {
                    deviceAlert.setLocation(moheLocation.getRoomId() + "");
                }
            }
            deviceAlert.setAlertType(dmcMoheService.convertAlertType(moheRecord.getType()));
            deviceAlert.setGroupId(getLoginAuthDto().getGroupId());
            deviceAlert.setDeviceId(dmcDevice.getId());
            deviceAlert.setDeviceNo(dmcDevice.getDeviceNo());
            deviceAlert.setCreatedTime(new Date());

            dmcDeviceAlertService.saveAlert(deviceAlert);


            OldmanBedRoomBuildingVo obrbv = null;
            switch (moheLocation.getBindType()) {
                case PhoneConstant.PHONE_ZONE_BIND_TYPE_CUSTOM :
                    break;
                case PhoneConstant.PHONE_ZONE_BIND_TYPE_OLDMAN :
                    obrbv = (OldmanBedRoomBuildingVo) redisTemplate.opsForValue().get(RedisKeyUtil.getOmcOldmanId(moheLocation.getOldmanId()));
                    break;
                case PhoneConstant.PHONE_ZONE_BIND_TYPE_BED :
                    obrbv = (OldmanBedRoomBuildingVo) redisTemplate.opsForValue().get(RedisKeyUtil.getOmcBedId(moheLocation.getBedId()));
                    break;
                case PhoneConstant.PHONE_ZONE_BIND_TYPE_ROOM :
                    RoomBuildingVo rbv = (RoomBuildingVo) redisTemplate.opsForValue().get(RedisKeyUtil.getOmcRoomId(moheLocation.getRoomId()));
                    BeanUtils.copyProperties(rbv, obrbv);
                    break;
            }

            dmcDeviceAlertService.sendDeviceAlertMsg(deviceAlert, obrbv);
        }

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE);
    }


    /**
     * 获取token
     */
    @RequestMapping(value = "/getToken", method = RequestMethod.POST)
    public Wrapper getToken(@RequestBody MoheDto moheDto) {
        log.info("/mohe/getToken,loginDto:" + moheDto.toString());
        // /mohe/getToken,loginDto:MoheDto(deviceId=5654, deviceNo=null, groupId=null, deviceType=0, deviceName=null, remark=null, bindOrUnBind=0, moheDeviceId=null, bindType=0, oldmanId=0, oldmanName=null, bedId=0, roomId=0, location=null, bindList=null)
        DmcMoheDeviceInfo moheDeviceInfo = null;
        try{
            moheDeviceInfo = (DmcMoheDeviceInfo) redisTemplate.opsForValue().get(moheDto.getDeviceId());
        }catch (Exception e) {
            log.error("netty server init error: {}", e.getMessage());
        }
        if (moheDeviceInfo != null) {
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "", moheDeviceInfo);
        }
        DmcMoheDeviceInfo info = moheDeviceInfoService.selectByKey(moheDto.getDeviceId());
        if (info != null) {
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "", info);
        }
        return WrapMapper.wrap(Wrapper.ERROR_CODE, "当前设备没有接入");
    }


    /**
     * 列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Wrapper list(@RequestBody MoheDto moheDto) {
        log.info("/mohe/list,loginDto:" + moheDto.toString());
        moheDto.setGroupId(getLoginAuthDto().getGroupId());
        moheDto.setDeviceType(DmcDeviceTypeEnum.MOHE_GATEWAY.getIndex());
        PageHelper.startPage(moheDto.getPageNum(), moheDto.getPageSize());
        List<MoheVO> list = dmcMoheService.list(moheDto);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("operation.success", null), new PageInfo<>(list));
    }

    /**
     * 新增
     */
//    @RequestMapping(value = "/save", method = RequestMethod.POST)
//    public Wrapper save(@RequestBody MoheDto moheDto) {
//        String sn = moheDto.getDeviceNo();
//        Example example = new Example(DmcDevice.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("deviceNo", sn);
//        List<DmcDevice> dmcDevices = dmcDeviceService.selectByExample(example);
//        if (CollectionUtil.isEmpty(dmcDevices)) {
//            log.info("当前设备未注册");
//            return WrapMapper.wrap(Wrapper.ERROR_CODE,"当前设备编码存在");
//        }
//
//        DmcDevice dmcDevice = new DmcDevice();
//        dmcDevice.setStatus(DmcDeviceStatusEnum.ENABLE.getKey());
//        dmcDevice.setCreator(getLoginAuthDto().getUserName());
//        dmcDevice.setCreatorId(getLoginAuthDto().getUserId());
//        dmcDevice.setLastOperator(getLoginAuthDto().getUserName());
//        dmcDevice.setLastOperatorId(getLoginAuthDto().getUserId());
//        dmcDevice.setCreatedTime(new Date());
//
//        dmcDevice.setDeviceName(moheDto.getDeviceName());
//        dmcDevice.setDeviceNo(moheDto.getDeviceNo());
//        dmcDevice.setRemark(moheDto.getRemark());
//        dmcDevice.setDeviceType(moheDto.getDeviceType());
//        dmcDeviceService.save(dmcDevice);
//        return WrapMapper.wrap(Wrapper.SUCCESS_CODE);
//    }

    /**
     * 编辑
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Wrapper edit(@RequestBody MoheDto moheDto) {
        log.info("/mohe/edit,loginDto:" + moheDto.toString());
        Long deviceId = moheDto.getDeviceId();
        DmcDevice dmcDevice = dmcDeviceService.selectByKey(deviceId);
        if (dmcDevice == null) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, "当前设备不存在");
        }
        dmcDevice.setRemark(moheDto.getRemark());
        dmcDevice.setDeviceName(moheDto.getDeviceName());
        dmcDevice.setUpdateTime(new Date());
        dmcDevice.setLastOperatorId(getLoginAuthDto().getUserId());
        dmcDevice.setLastOperator(getLoginAuthDto().getUserName());
        dmcDeviceService.update(dmcDevice);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE);
    }

    /**
     * 查询魔盒
     */
    @RequestMapping(value = "/queyrMohe", method = RequestMethod.POST)
    public Wrapper queyrMohe(@RequestBody MoheDto moheDto) {
        log.info("/mohe/queyrMohe,loginDto:" + moheDto.toString());
        Example example = new Example(DmcDevice.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("groupId", getLoginAuthDto());
        criteria.andEqualTo("deviceType", DmcDeviceTypeEnum.MOHE_GATEWAY.getIndex());
        List<DmcDevice> dmcDevices = dmcDeviceService.selectByExample(example);
        if (CollectionUtil.isEmpty(dmcDevices)) {
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "");
        }
        List<String> collect = dmcDevices.stream().map(k -> k.getDeviceNo()).collect(Collectors.toList());
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "", collect);
    }

    /**
     * 设备 绑定解绑位置
     */
    @RequestMapping(value = "/bindOrUnBind", method = RequestMethod.POST)
    public Wrapper bindOrUnBind(@RequestBody MoheDto moheDto) {
        log.info("/mohe/bindOrUnBind,loginDto:" + moheDto.toString());
        int bindOrUnBind = moheDto.getBindOrUnBind();

        if (bindOrUnBind == 0) {
            // 解绑
            DmcCsunMoheLocation moheLocation = moheLocationService.selectByKey(moheDto.getDeviceId());
            if (moheLocation == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "当前设备不存在");
            }
            moheLocationService.delete(moheLocation);


        } else if (bindOrUnBind == 1) {
            // 绑定
            DmcCsunMoheLocation moheLocation = new DmcCsunMoheLocation();
            BeanUtils.copyProperties(moheDto, moheLocation);
            //moheLocation.setDeviceId(moheDto.getDeviceId().intValue());
//            moheLocation.setBindType(moheDto.getBindType());
//            moheLocation.setOldmanId(moheDto.getOldmanId());
//            moheLocation.setOldmanName(moheDto.getOldmanName());
//            moheLocation.setBedId(moheDto.getBedId());
//            moheLocation.setRoomId(moheDto.getRoomId());
//            moheLocation.setLocation(moheDto.getLocation());

            moheLocation.setCreatedTime(new Date());
            moheLocation.setCreator(getLoginAuthDto().getUserName());
            moheLocation.setCreatorId(getLoginAuthDto().getUserId());
            int save = moheLocationService.save(moheLocation);
            if (save > 0) {
                return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "操作成功");
            }
            return WrapMapper.wrap(Wrapper.ERROR_CODE, "操作失败");

        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE);
    }

    /**
     * 报警器绑定解绑魔盒
     */
    @RequestMapping(value = "/bindOrUnBindMohe", method = RequestMethod.POST)
    public Wrapper bindOrUnBindMohe(@RequestBody MoheDto moheDto) {
        log.info("/mohe/bindOrUnBindMohe,loginDto:" + moheDto.toString());
        int bindOrUnBind = moheDto.getBindOrUnBind();

        if (bindOrUnBind == 0) {
            // 解绑
            DmcMoheDeviceRelation moheDeviceRelation = new DmcMoheDeviceRelation();
            moheDeviceRelation.setDeviceId(moheDto.getDeviceId());
//            moheDeviceRelation.setMoheDeviceId(moheDto.getMoheDeviceId());
            List<DmcMoheDeviceRelation> select = moheDeviceRelationService.select(moheDeviceRelation);
            if (CollectionUtil.isEmpty(select)) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "解绑异常：当前设备没有绑定关系");
            }

            int delete = moheDeviceRelationService.delete(moheDeviceRelation);
            if (delete < 1) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "解绑失败");
            }

            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "解绑成功");

        } else if (bindOrUnBind == 1) {
            // 绑定
            DmcMoheDeviceRelation moheDeviceRelation = new DmcMoheDeviceRelation();
            moheDeviceRelation.setDeviceId(moheDto.getDeviceId());
            moheDeviceRelation.setMoheDeviceId(moheDto.getMoheDeviceId());
            int save = moheDeviceRelationService.save(moheDeviceRelation);
            if (save < 1) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "绑定失败");
            }

            return WrapMapper.wrap(Wrapper.ERROR_CODE, "绑定成功");
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "");
    }

    /**
     * 获取报警器设备信息
     */
    @RequestMapping(value = "/queryDeviceInfo", method = RequestMethod.POST)
    public Wrapper queryDeviceInfo(@RequestBody MoheDto moheDto) {
        log.info("/mohe/queryDeviceInfo,loginDto:" + moheDto.toString());
        moheDto.setGroupId(getLoginAuthDto().getGroupId());

        List<MoheVO> list = dmcMoheService.list(moheDto);
        List<Long> selectBind = list.stream().filter(k -> k.getBindDevice() == 1).map(j -> {
            return j.getId();
        }).collect(Collectors.toList());

        List<Long> selectUnBind = list.stream().filter(k -> k.getBindDevice() == 0).map(j -> {
            return j.getId();
        }).collect(Collectors.toList());


        MoheVO moheVO = new MoheVO();
        moheVO.setBindDeviceId(selectBind);
        moheVO.setUnBindDeviceId(selectUnBind);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "", moheVO);
    }

    /**
     * 魔盒绑定设备
     */
    @RequestMapping(value = "/bindDevice", method = RequestMethod.POST)
    public Wrapper bindDevice(@RequestBody MoheDto moheDto) {
        log.info("/mohe/bindDevice,loginDto:" + moheDto.toString());
        List<Long> bindList = moheDto.getBindList();

        DmcMoheDeviceRelation dmcMoheDeviceRelation = new DmcMoheDeviceRelation();
        dmcMoheDeviceRelation.setMoheDeviceId(moheDto.getMoheDeviceId());
        moheDeviceRelationService.delete(dmcMoheDeviceRelation);

        if (CollectionUtil.isEmpty(bindList)) {
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "操作成功");
        } else {
            for (Long deviceId : bindList) {
                DmcMoheDeviceRelation deviceRelation = new DmcMoheDeviceRelation();
                deviceRelation.setMoheDeviceId(moheDto.getMoheDeviceId());
                deviceRelation.setDeviceId(deviceId);
                moheDeviceRelationService.save(deviceRelation);
            }

            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "操作成功");
        }


    }

}
